/*
 SAMPLE FORM
*/

require('./common');

exports.load = function(req, res){
	res.render("workflow",{
		title: "Workflow"
	});
	
}

exports.save = function(req, res){
	//res.send(req.body.content);

	//GET ALL FIELDS
	var formName = req.body.tblname;
	var description = req.body.description;
	var fields = req.body.fields.split(",");
	var lFields =  req.body.fields;
	
	var tblName = createTableName(formName);
	console.log("tblname = " + tblName);
	console.log("description = " + description);
	console.log("fields = " + lFields);
	//CREATE TABLE AND FIELDS
	createTable(tblName,fields);
	//SAVE WORKSPACE
	saveWorkspace(formName, tblName, description, req.body.content);
	//res.send("Workspace Saved.");
	res.redirect('/');
	
}

function createTable(tblName, fields){

	var createSQL = "CREATE TABLE " + tblName + " ( ";
	
	createSQL +=" ID int PRIMARY KEY AUTO_INCREMENT, ";
	
	for(var ctr=0;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		createSQL += fields[ctr] + " VARCHAR(100), ";
		}else{
		createSQL += fields[ctr] + " VARCHAR(100)";
		}
	}
	
	createSQL+=")";
	console.log("Creating table...." + tblName);
	conn.query(createSQL);
	console.log("Done creating table..." + tblName);
}

function saveWorkspace(formName, name, description, content){
	var strSQL = "INSERT INTO tblworkspace (FormName, Name, Description, Content, DateCreated, DateUpdated, CreatedBy, UpdatedBy) VALUES ('" + formName + "', '" + name +"','" + description + "','" + content + "', Date(Now()),Date(Now()),'Stephen Curry', 'Stephen Curry')";
	
	conn.query(strSQL);
}


function createTableName(tblName){
	return 'tbl_' + tblName.replace(/ /g,"_");
}